package com.lyx.gateway.config;

import com.lyx.common.constant.RedisContant;
import com.lyx.common.exception.BusinessException;
import com.lyx.common.exception.ExceptionEnum;
import com.lyx.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * @author 14667
 * @date 2022/8/4 16:23
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    private static final String AUTHORIZE_TOKEN = "token";

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1. 获取请求
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("url:"+request.getURI().getPath());
        //2. 则获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3. 如果是登录请求则放行
        if (request.getURI().getPath().contains("/user/users")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/phone")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/sms")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/wechat")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/chapter")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/addQuestion")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/updateQuestion")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/deleteQuestion")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/selectQuestionByIdAndChapterId")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/indexSearch")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/selectAll")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/question/shcduleUpdateRank")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/rank")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/scheuled")) {
            return chain.filter(exchange);
        }
        if (request.getURI().getPath().contains("/test")) {
            return chain.filter(exchange);
        }
        String token = null;
        try {
            //4. 获取请求头
            HttpHeaders headers = request.getHeaders();
            //5. 请求头中获取令牌
            token = headers.getFirst(AUTHORIZE_TOKEN);
            System.out.println(token);
        }catch (Exception e){
            throw new BusinessException(ExceptionEnum.TOKEN_ANALYSIS_ERROR);
        }

        //6. 判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException(ExceptionEnum.USER_NOT_LOGIN);
        }

        //9. 如果请求头中有令牌则解析令牌
        try {
            boolean b = JwtUtils.checkToken(token);
            if(b){
                Jws<Claims> claimsJws = Jwts.parser().setSigningKey(JwtUtils.APP_SECRET).parseClaimsJws(token);
                Claims claims = claimsJws.getBody();
                String id = (String)claims.get("id");
                Integer userId = null;
                if(!id.equals("")){
                    userId = Integer.parseInt(id);
                    String s = redisTemplate.opsForValue().get(String.format(RedisContant.TOKEN, userId));
                    if(!token.equals(s)){
                        throw new BusinessException(ExceptionEnum.USER_NOT_LOGIN);
                    }
                    String finalUserId = String.valueOf(userId);
                    Consumer<HttpHeaders> headers = httpHeaders -> {
                        httpHeaders.add(RedisContant.USER_ID, finalUserId);
                    };
                    request.mutate().headers(headers).build();
                }else{
                    throw new BusinessException(ExceptionEnum.USER_NOT_LOGIN);
                }

            }else{
                throw new BusinessException(ExceptionEnum.USER_NOT_LOGIN);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //10. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            throw new BusinessException(ExceptionEnum.USER_NOT_LOGIN);
        }
        //12. 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
